package com.example.demo.util;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.ZipUtil;

import java.io.*;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

/**
 * zip文件的解压/压缩/提取/添加等功能
 *
 * @author: zyc
 */
public class ZipUtils extends ZipUtil {


    public static void main(String[] args) throws Exception {
        test3();
    }

    public static void test3() throws Exception {
        // 向zip文件中写入一个文件夹
        File file = new File("D:\\Users\\zyc\\Downloads\\2020101027-zyc测试1培训班资料22.zip");
        file.delete();
        file.createNewFile();
        ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(file));


        ZipEntry zipEntry = new ZipEntry("123/");
        zipOutputStream.putNextEntry(zipEntry);
        zipOutputStream.closeEntry();
        zipOutputStream.close();
    }

    public static void test2() throws Exception {
        // 向该文件中以zip的方式写入数据
        String path = "D:\\Company\\项目\\四川电力\\12 培训项目验收意见表2.zip";
        new File(path).delete();
        new File(path).createNewFile();
        ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(new File(path)));


        ZipEntry zipEntry = new ZipEntry("word/document.txt");
        zipOutputStream.putNextEntry(zipEntry);
        StreamUtil.copy("123".getBytes(), zipOutputStream);

        zipEntry = new ZipEntry("document.txt");
        zipOutputStream.putNextEntry(zipEntry);
        StreamUtil.copy("123321".getBytes(), zipOutputStream);
        zipOutputStream.close();
    }

    public static void test() throws Exception {
        String                          path            = "D:\\Company\\项目\\四川电力\\12 培训项目验收意见表.docx";
        ZipOutputStream                 zipOutputStream = new ZipOutputStream(new FileOutputStream(new File("D:\\Company\\项目\\四川电力\\12 培训项目验收意见表2.docx")));
        String                          target          = "word/document.xml";
        ZipFile                         zipFile         = new ZipFile(path);
        Enumeration<? extends ZipEntry> entries         = zipFile.entries();
        ZipEntry                        zipEntry;
        InputStream                     inputStream;
        while (entries.hasMoreElements()) {
            zipEntry = entries.nextElement();
            inputStream = zipFile.getInputStream(zipEntry);
            // 获取到对应的input流
            zipOutputStream.putNextEntry(new ZipEntry(zipEntry.getName()));
            StreamUtil.copy(inputStream, zipOutputStream);
            inputStream.close();
            zipOutputStream.closeEntry();
        }
        zipOutputStream.close();
    }


}
